from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, session
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from ..extensions import db
from ..models import User
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# 修改蓝图名称为 auth_bp 以避免与模块名冲突
auth_bp = Blueprint('auth', __name__)

# 模拟用户数据库
users = {
    'admin': {
        'password': generate_password_hash('admin123'),
        'name': '管理员',
        'role': 'admin',
        'avatar': '/static/images/avatar.png'
    }
}

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    try:
        if request.method == 'POST':
            username = request.form.get('username')
            password = request.form.get('password')
            
            user = User.query.filter_by(username=username).first()
            
            if user and check_password_hash(user.password_hash, password):
                login_user(user)
                next_page = request.args.get('next')
                return redirect(next_page or url_for('main.index'))
            else:
                flash('用户名或密码错误')
        
        return render_template('auth/login.html')
    except Exception as e:
        logger.exception("登录过程出错：")
        flash('系统错误，请稍后重试')
        return render_template('auth/login.html'), 500

@auth_bp.route('/logout')
@login_required
def logout():
    try:
        logout_user()
        return redirect(url_for('main.index'))
    except Exception as e:
        logger.exception("登出过程出错：")
        return "登出失败", 500

# 添加一个初始用户的路由（仅用于测试）
@auth_bp.route('/init')
def init():
    try:
        if User.query.first() is None:
            user = User(
                username='admin',
                password_hash=generate_password_hash('admin')
            )
            db.session.add(user)
            db.session.commit()
            return '初始用户已创建'
        return '用户已存在'
    except Exception as e:
        logger.exception("初始化用户出错：")
        return "初始化失败", 500

@auth_bp.route('/register')
def register():
    return 'Register Page'

@auth_bp.route('/api/auth/login', methods=['POST'])
def login_api():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'error': '用户名和密码不能为空'}), 400
        
    user = users.get(username)
    if user and check_password_hash(user['password'], password):
        session['user'] = {
            'username': username,
            'name': user['name'],
            'role': user['role'],
            'avatar': user['avatar']
        }
        return jsonify({'message': '登录成功', 'user': session['user']})
    
    return jsonify({'error': '用户名或密码错误'}), 401

@auth_bp.route('/api/auth/logout', methods=['POST'])
def logout_api():
    session.pop('user', None)
    return jsonify({'message': '退出成功'})

@auth_bp.route('/api/auth/check', methods=['GET'])
def check_auth():
    user = session.get('user')
    if user:
        return jsonify({'authenticated': True, 'user': user})
    return jsonify({'authenticated': False}), 401

# ... 其他路由 ... 